﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Project_2._2.Models;
using Project_2._2.ViewModels;
using Project_2._2.Extra;
using System.IO;
using System.Web.Security;
using PagedList;
using PagedList.Mvc;
namespace Project_2._2.Controllers
{
    public class DefaultController : Controller
    {
        private QuanLyThueXeEntities db = new QuanLyThueXeEntities();
        private Common cm = new Common();
        //
        // GET: /Default/
        public ActionResult TrangChu()
        {
            var dv = (from p in db.DichVuThueXes select p).ToList();
            ViewBag.alert = "Xin chào bạn.";
            return View(dv);
        }
        public ActionResult BaoGia() 
        {
            return View();
        }
        public ActionResult GioiThieu()
        {
            return View();
        }

        public ActionResult LienHe()
        {
            return View();
        }
        [HttpPost]
        public ActionResult LienHe(FeedbackViewModels feedback)
        {
            try
            {
                //Thêm ý kiến khách hàng
                if (ModelState.IsValid)
                {
                    if (feedback.captcha.CompareTo(Session["Captcha"]) != 0)
                        ModelState.AddModelError("Captcha", "Mã xác nhận không chính xác.");
                    else
                    {
                        //Lấy ngày tháng hiện tại
                        string layngay = DateTime.Now.ToString();
                        DateTime sngayHT = Convert.ToDateTime(layngay);

                        Feedback fd = new Feedback();
                        fd.HoTen = feedback.HoTen;
                        fd.Email = feedback.Email;
                        fd.TieuDe = feedback.TieuDe;
                        fd.NoiDung = feedback.NoiDung;
                        fd.NgayGui = sngayHT;
                        fd.TrangThai = false;
                        fd.isDelete = false;
                        // Add vao Database
                        db.Feedbacks.Add(fd);
                        db.SaveChanges();
                        //return RedirectToAction("Default","Default");
                        //ViewBag.SucessMessage = "Cám ơn bạn đã đóng góp ý kiến...!";
                        ModelState.Clear();
                        ViewBag.alert = "Cám ơn bạn đã đóng góp ý kiến...!";
                    }
                }
                return View(feedback);
            }
            catch (Exception)
            {
                return RedirectToAction("SystemErrors", "Default");
            }
            
        }

        public ActionResult GopY()
        {
            return View();
        }
        public ActionResult DatXe() 
        {
            return View();
        }
        [HttpPost]
        public ActionResult DatXe(BookCarsViewModel bookcar)
        {
            //Thêm Đơn Đặt Xe khách hàng
            try
            {
                if (ModelState.IsValid)
                {
                    if (string.IsNullOrEmpty(bookcar.HoTen) || string.IsNullOrEmpty(bookcar.DienThoai)) 
                    {
                        ViewBag.dichvuid = bookcar.DichVuId;
                        return View();
                    }
                    else
                    {
                        if (bookcar.captcha.CompareTo(Session["Captcha"]) != 0)
                            ModelState.AddModelError("Captcha", "Mã xác nhận không chính xác.");
                        else
                        {
                            //Lấy ngày tháng hiện tại
                            string layngay = DateTime.Now.ToString();
                            DateTime sngayHT = Convert.ToDateTime(layngay);

                            DatXe dx = new DatXe();
                            dx.DichVuId = int.Parse(bookcar.DichVuId);
                            dx.XeId = int.Parse(bookcar.XeId);
                            dx.HoTen = bookcar.HoTen;
                            dx.DiaChi = bookcar.DiaChi;
                            dx.Email = bookcar.Email;
                            dx.DienThoai = bookcar.DienThoai;
                            dx.YeuCauKhac = bookcar.YeuCau;
                            dx.NgayDatXe = sngayHT;
                            dx.Duyet = false;
                            dx.isDelete = false;

                            db.DatXes.Add(dx);
                            db.SaveChanges();

                            ViewBag.SucessMessage = "Bạn đã đặt Xe Thành Công . Chúng tôi sẽ liên hệ với các bạn trong thời gian sớm nhất để hoàn tắt quá trình đặt xe .!";
                        }
                    }
                  
                }

            }
            catch (Exception) 
            {
                return RedirectToAction("SystemErrors", "Default");
            }
             return RedirectToAction("DatxeThanhCong", "Default");
        
        }
        public ActionResult TinTuc()
        {
            TinTuc_ViewModels vm = new TinTuc_ViewModels();
            return View(vm);
        }

        public ActionResult DatXe_Nhanh(int carid, int dvid , decimal giaxe) 
        {
            try
            {
                ViewBag.xeid = carid;
                ViewBag.dvid = dvid;
                ViewBag.giaxe = giaxe;
            }
            catch (Exception)
            {
                return RedirectToAction("SystemErrors", "Default");
            }
            return View();
        }
        [HttpPost]
        public ActionResult DatXe_Nhanh(BookCarsViewModel bookcar) 
        {
          
            //Thêm Đơn Đặt Xe khách hàng
            try
            {
                if (ModelState.IsValid)
                {
                    if (bookcar.captcha.CompareTo(Session["Captcha"]) != 0)
                        ModelState.AddModelError("Captcha", "Mã xác nhận không chính xác.");
                    else
                    {
                        //Lấy ngày tháng hiện tại
                        string layngay = DateTime.Now.ToString();
                        DateTime sngayHT = Convert.ToDateTime(layngay);

                        DatXe dx = new DatXe();
                        dx.DichVuId = int.Parse(bookcar.DichVuId);
                        dx.XeId = int.Parse(bookcar.XeId);
                        dx.HoTen = bookcar.HoTen;
                        dx.DiaChi = bookcar.DiaChi;
                        dx.Email = bookcar.Email;
                        dx.DienThoai = bookcar.DienThoai;
                        dx.YeuCauKhac = bookcar.YeuCau;
                        dx.NgayDatXe = sngayHT;
                        dx.Duyet = false;
                        dx.isDelete = false;

                        db.DatXes.Add(dx);
                        db.SaveChanges();

                        ViewBag.SucessMessage = "Bạn đã đặt Xe Thành Công . Chúng tôi sẽ liên hệ với các bạn trong thời gian sớm nhất để hoàn tất đặt xe .!";

                    }
                }
            }
            catch (Exception)
            {
                return RedirectToAction("SystemErrors", "Default");
            }
           
            return RedirectToAction("DatxeThanhCong", "Default");
        }
        public ActionResult DatxeThanhCong() 
        {
            return View();
        }

        public ActionResult ChoThueThanhCong()
        {
            return View();
        }
        public ActionResult SystemErrors() 
        {
            return View();
        }
        public ActionResult KH_DangXe()
        {
            return View();
        }
        [HttpPost , ValidateAntiForgeryToken]
        public ActionResult KH_DangXe(CarList_ViewModel Cars, HttpPostedFileBase uploadFile) 
        {
            if (!Request.IsAuthenticated)
            {
                return RedirectToAction("DangNhap", "TaiKhoan");
            }
            else
            {
                try
                {
                    if (ModelState.IsValid) 
                    {
                        if (Cars.captcha.CompareTo(Session["Captcha"]) != 0)
                            ModelState.AddModelError("Captcha", "Mã xác nhận không chính xác.");
                        else
                        {

                            Xe car = new Xe();
                            var fileName = "";
                            GiaXe giaxe = new GiaXe();
                            var idperson = (from p in db.People where p.TenDangNhap == User.Identity.Name select p).FirstOrDefault();
                            if (uploadFile != null && uploadFile.ContentLength > 0)
                            {
                                fileName = Path.GetFileName(uploadFile.FileName);
                                var path = Path.Combine(Server.MapPath("~/Images/Cars/"), fileName); uploadFile.SaveAs(path);

                            }
                            car.HinhAnhDaiDien = fileName.ToString();
                            car.PersonId = idperson.PersonId;
                            car.ThuongHieuId = Cars.ThuongHieuID;
                            car.LoaiXeId = Cars.LoaiID;
                            car.TenXe = Cars.name;
                            car.DoiXe = Cars.DoiXe;
                            car.DongXe = Cars.DongXe;
                            car.TaiXe = Cars.Taixe;
                            car.MauXe = Cars.Color;
                            car.PhuTroNgoaiGio = Cars.PhuTroNgoaiGio;
                            car.PhuTroQuaKm = Cars.PhuTroKM;
                            car.SuDungCuoiTuan = Cars.SuDungCuoiTuan;
                            car.ChiTiet = HttpUtility.HtmlDecode(Cars.ChiTiet);
                            car.Video = HttpUtility.HtmlDecode(Cars.Video);
                            car.TrangThai = Cars.TThai;
                            car.Duyet = false;
                            car.isDelete = false;
                            db.Xes.Add(car);
                            db.SaveChanges();

                            var idxe = (from p in db.Xes select p).Take(1).OrderByDescending(m => m.XeId).FirstOrDefault();

                            giaxe.DichVuId = Cars.dichvuID;
                            giaxe.XeId = idxe.XeId;
                            giaxe.Gia = Cars.Gia;
                            giaxe.isDelete = false;
                            db.GiaXes.Add(giaxe);
                            db.SaveChanges();
                            return RedirectToAction("ChoThueThanhCong", "Default");
                        }
                    }
                    else
                    {
                        return View();
                    }
                }
                catch (Exception)
                {
                    return RedirectToAction("SystemErrors", "Default");
                }
                
            }
            return View();
        }

        public ActionResult ChoThueKhachHang(int? page, string rd, string Record, string key, string SBy, string SType)
        {
            try
            {
                    var idperson = (from p in db.People where p.TenDangNhap == User.Identity.Name select p).FirstOrDefault();
                    if (rd != null)
                    {
                        int soDong = int.Parse(rd);
                        string k = key;
                        string b = SBy;
                        string t = SType;
                        IPagedList<Xe> cars = null;

                        if (!string.IsNullOrEmpty(k) && b != "0")
                        {
                            ViewBag.Key = k;
                            ViewBag.SBy = b;
                            ViewBag.SType = t;

                            switch (b)
                            {
                                case "Name":
                                    if (t == "1")
                                        cars = (from p in db.Xes where p.PersonId == idperson.PersonId && p.TenXe.Contains(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                                    else
                                    {
                                        cars = (from p in db.Xes where p.PersonId == idperson.PersonId && p.TenXe.Equals(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                                    }
                                    break;
                                case "DongXe":
                                    if (t == "1")
                                        cars = (from p in db.Xes where p.PersonId == idperson.PersonId && p.DongXe.Contains(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                                    else
                                    {
                                        cars = (from p in db.Xes where p.PersonId == idperson.PersonId && p.DongXe.Equals(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                                    }
                                    break;
                                case "DoiXe":
                                    if (t == "1")
                                        cars = (from p in db.Xes where p.PersonId == idperson.PersonId && p.DoiXe.Contains(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                                    else
                                    {
                                        cars = (from p in db.Xes where p.PersonId == idperson.PersonId && p.DoiXe.Equals(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                                    }
                                    break;
                            }
                        }
                        else
                        {
                            cars = (from p in db.Xes where p.PersonId == idperson.PersonId && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                        }

                        ViewBag.record = rd;
                        return View(cars);
                    }
                    else
                    {
                        var cars = (from p in db.Xes where p.PersonId == idperson.PersonId && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, 10);
                        return View(cars);
                    }
                
            }
            catch (Exception)
            {
                return RedirectToAction("SystemErrors", "Default");
            }  
        }
        //POST
        [HttpPost]
        public ActionResult ChoThueKhachHang(FormCollection col, int? page)
        {
            try
            {
                int soDong = 10;
                string SearchBy = col["SearchBy"];
                string SearchType = col["SearchType"];
                string key = col["KeyWorld"];
                IPagedList<Xe> cars = null;
                var idperson = (from p in db.People where p.TenDangNhap == User.Identity.Name select p).FirstOrDefault();
                //
                ViewBag.Key = key;
                ViewBag.SBy = SearchBy;
                ViewBag.SType = SearchType;
                ViewBag.record = soDong.ToString();

                if (string.IsNullOrEmpty(key))
                {
                    cars = (from p in db.Xes where p.PersonId == idperson.PersonId && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                    return View(cars);
                }
                else
                {
                    switch (SearchBy)
                    {
                        case "Name":
                            if (SearchType == "1")
                                cars = (from p in db.Xes where p.PersonId == idperson.PersonId && p.TenXe.Contains(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                            else
                            {
                                cars = (from p in db.Xes where p.PersonId == idperson.PersonId && p.TenXe.Equals(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                            }
                            break;
                        case "DoiXe":
                            if (SearchType == "1")
                                cars = (from p in db.Xes where p.PersonId == idperson.PersonId && p.DoiXe.Contains(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                            else
                            {
                                cars = (from p in db.Xes where p.PersonId == idperson.PersonId && p.DoiXe.Equals(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                            }
                            break;
                        case "DongXe":
                            if (SearchType == "1")
                                cars = (from p in db.Xes where p.PersonId == idperson.PersonId && p.DongXe.Contains(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                            else
                            {
                                cars = (from p in db.Xes where p.PersonId == idperson.PersonId && p.DongXe.Equals(key) && p.isDelete == false select p).OrderByDescending(m => m.XeId).ToList().ToPagedList(page ?? 1, soDong);
                            }
                            break;
                        default:
                            ViewBag.erorr = "Không có dữ liệu .... ";
                            break;
                    }
                    return View(cars);
                }
            }
            catch (Exception)
            {
                return RedirectToAction("SystemErrors", "Default");
            }

        }
       
        public ActionResult ChiTiet_ChoThueXeKH(int id)
        {
            CarList_ViewModel carslist = new CarList_ViewModel();

            var cars = (from xe in db.Xes
                        join kh in db.People on xe.PersonId equals kh.PersonId
                        join gia in db.GiaXes on xe.XeId equals gia.XeId
                        join dv in db.DichVuThueXes on gia.DichVuId equals dv.DichVuId
                        join loai in db.LoaiXes on xe.LoaiXeId equals loai.LoaiXeId
                        join th in db.ThuongHieux on xe.ThuongHieuId equals th.ThuongHieuId
                        where xe.XeId == id && xe.isDelete == false
                        select new
                        {
                            id = xe.XeId,
                            name = xe.TenXe,
                            THieuID = th.ThuongHieuId,
                            tenloai = loai.TenLoaiXe,
                            tenhieu = th.TenThuongHieu,
                            Doixe = xe.DoiXe,
                            DongXe = xe.DongXe,
                            Color = xe.MauXe,
                            LoaiID = loai.LoaiXeId,
                            khID = kh.PersonId,
                            tenKH = kh.HoTen,
                            Gia = gia.Gia,
                            Hinh = xe.HinhAnhDaiDien,
                            TThai = xe.TrangThai,
                            tenDV = dv.TenDichVu,
                            iddv = dv.DichVuId,
                            chitiet = xe.ChiTiet,
                            phutroKM = xe.PhuTroQuaKm,
                            phutroNgoaiGio = xe.PhuTroNgoaiGio,
                            sudungcuoituan = xe.SuDungCuoiTuan,
                            hinhanhdaidien = xe.HinhAnhDaiDien,
                            video = xe.Video,
                            trangthai = xe.TrangThai,
                            duyet = xe.Duyet,

                        }).ToList();

            foreach (var item in cars)
            {
                carslist.id = item.id;
                carslist.name = item.name;
                carslist.ThuongHieuID = item.THieuID;
                carslist.Loai = item.tenloai;
                carslist.THieu = item.tenhieu;
                carslist.DoiXe = item.Doixe;
                carslist.DongXe = item.DongXe;
                carslist.Color = item.Color;
                carslist.LoaiID = item.LoaiID;
                carslist.TThai = item.TThai;
                carslist.Gia = item.Gia;
                carslist.khachHangID = item.khID;
                carslist.TenKH = item.tenKH;
                carslist.hinh = item.Hinh;
                carslist.dichvuID = item.iddv;
                carslist.tendichvu = item.tenDV;
                carslist.ChiTiet = item.chitiet;
                carslist.PhuTroKM = item.phutroKM;
                carslist.PhuTroNgoaiGio = item.phutroNgoaiGio;
                carslist.SuDungCuoiTuan = item.sudungcuoituan;
                carslist.Video = item.video;
                carslist.TThai = item.trangthai;
                carslist.duyet = item.duyet;
                carslist.hinh = item.hinhanhdaidien;
            }

            return View(carslist);
        }
        public ActionResult UpdateXeKH(int id)
        {
            CarList_ViewModel carslist = new CarList_ViewModel();
        
                    try
                    {
                        var idperson = (from p in db.People where p.TenDangNhap == User.Identity.Name select p).FirstOrDefault();

                        var cars = (from xe in db.Xes
                                    join kh in db.People on xe.PersonId equals kh.PersonId
                                    join gia in db.GiaXes on xe.XeId equals gia.XeId
                                    join dv in db.DichVuThueXes on gia.DichVuId equals dv.DichVuId
                                    join loai in db.LoaiXes on xe.LoaiXeId equals loai.LoaiXeId
                                    join th in db.ThuongHieux on xe.ThuongHieuId equals th.ThuongHieuId
                                    where xe.XeId == id  && kh.PersonId == idperson.PersonId && xe.isDelete == false

                                    select new
                                    {
                                        id = xe.XeId,
                                        name = xe.TenXe,
                                        THieuID = th.ThuongHieuId,
                                        tenloai = loai.TenLoaiXe,
                                        tenhieu = th.TenThuongHieu,
                                        Doixe = xe.DoiXe,
                                        DongXe = xe.DongXe,
                                        Color = xe.MauXe,
                                        LoaiID = loai.LoaiXeId,
                                        khID = kh.PersonId,
                                        tenKH = kh.HoTen,
                                        Gia = gia.Gia,
                                        Hinh = xe.HinhAnhDaiDien,
                                        TThai = xe.TrangThai,
                                        tenDV = dv.TenDichVu,
                                        iddv = dv.DichVuId,
                                        chitiet = xe.ChiTiet,
                                        phutroKM = xe.PhuTroQuaKm,
                                        phutroNgoaiGio = xe.PhuTroNgoaiGio,
                                        sudungcuoituan = xe.SuDungCuoiTuan,
                                        hinhanhdaidien = xe.HinhAnhDaiDien,
                                        video = xe.Video,
                                        trangthai = xe.TrangThai,
                                        duyet = xe.Duyet,

                                    }).FirstOrDefault();

                        carslist.id = cars.id;
                        carslist.name = cars.name;
                        carslist.ThuongHieuID = cars.THieuID;
                        carslist.Loai = cars.tenloai;
                        carslist.THieu = cars.tenhieu;
                        carslist.DoiXe = cars.Doixe;
                        carslist.DongXe = cars.DongXe;
                        carslist.Color = cars.Color;
                        carslist.LoaiID = cars.LoaiID;
                        carslist.TThai = cars.TThai;
                        carslist.Gia = cars.Gia;
                        carslist.khachHangID = cars.khID;
                        carslist.TenKH = cars.tenKH;
                        carslist.hinh = cars.Hinh;
                        carslist.dichvuID = cars.iddv;
                        carslist.tendichvu = cars.tenDV;
                        carslist.ChiTiet = cars.chitiet;
                        carslist.PhuTroKM = cars.phutroKM;
                        carslist.PhuTroNgoaiGio = cars.phutroNgoaiGio;
                        carslist.SuDungCuoiTuan = cars.sudungcuoituan;
                        carslist.Video = cars.video;
                        carslist.TThai = cars.trangthai;
                        carslist.duyet = cars.duyet;
                        carslist.hinh = cars.hinhanhdaidien;

                        return View(carslist);
                    }
                    catch (Exception)
                    {
                        return RedirectToAction("SystemErrors", "Default");
                    }

        }
        [HttpPost]
        public ActionResult UpdateXeKH(CarList_ViewModel Cars, HttpPostedFileBase uploadFile)
        {
            try
            {
                if (Cars.captcha.CompareTo(Session["Captcha"]) != 0)

                    ModelState.AddModelError("Captcha", "Mã xác nhận không chính xác.");
                else
                {
                    var idperson = (from p in db.People where p.TenDangNhap == User.Identity.Name select p).FirstOrDefault();

                    var car = (from p in db.Xes where p.XeId == Cars.id select p).FirstOrDefault();

                    var giaxe = (from p in db.GiaXes where p.XeId == Cars.id select p).FirstOrDefault();

                    var fileName = car.HinhAnhDaiDien;

                    if (uploadFile != null && uploadFile.ContentLength > 0)
                    {
                        fileName = Path.GetFileName(uploadFile.FileName);
                        var path = Path.Combine(Server.MapPath("~/Images/Cars/"), fileName); uploadFile.SaveAs(path);
                    }

                    car.HinhAnhDaiDien = fileName.ToString();
                    car.PersonId = idperson.PersonId;
                    car.ThuongHieuId = Cars.ThuongHieuID;
                    car.LoaiXeId = Cars.LoaiID;
                    car.TenXe = Cars.name;
                    car.DoiXe = Cars.DoiXe;
                    car.DongXe = Cars.DongXe;
                    car.TaiXe = Cars.Taixe;
                    car.MauXe = Cars.Color;
                    car.PhuTroNgoaiGio = Cars.PhuTroNgoaiGio;
                    car.PhuTroQuaKm = Cars.PhuTroKM;
                    car.SuDungCuoiTuan = Cars.SuDungCuoiTuan;
                    car.ChiTiet = Cars.ChiTiet;
                    car.Video = Cars.Video;
                    car.TrangThai = Cars.TThai;
                    car.Duyet = true;
                    car.isDelete = false;
                    UpdateModel(car);
                    db.SaveChanges();

                    giaxe.DichVuId = Cars.dichvuID;
                    giaxe.XeId = Cars.id;
                    giaxe.Gia = Cars.Gia;
                    giaxe.isDelete = false;
                    UpdateModel(giaxe);
                    db.SaveChanges();
                    return RedirectToAction("ChoThueKhachHang", "Default");
                }

            }
            catch (Exception)
            {
                return RedirectToAction("SystemErrors", "Default");
            }

            return View();
        }
        public ActionResult DeleteXeKH(int id)
        {
            try
            {
                Xe car = (from p in db.Xes where p.XeId == id select p).First();
                car.isDelete = true;
                UpdateModel(car);
                db.SaveChanges();
                return RedirectToAction("ChoThueKhachHang", "Default");
            }
            catch (Exception)
            {
                return RedirectToAction("SystemErrors", "Default");
            }
        }
        public ActionResult Multi_DeleteXeKH(IEnumerable<int> XeIdsToDelete)
        {
                    try
                    {
                        var Xe_delete = db.Xes.Where(x => XeIdsToDelete.Contains(x.XeId)).ToList();
                        foreach (var car in Xe_delete)
                        {
                            car.isDelete = true;
                            UpdateModel(car);
                            db.SaveChanges();
                        }
                        return RedirectToAction("ChoThueKhachHang", "Default");
                    }
                    catch (Exception)
                    {
                        return RedirectToAction("SystemErrors", "Default");
                    }
               
            

        }

        public ActionResult ThongKe() 
        {
            return View();
        }
    }
}
